package in.muton.edushare.validators.formvalidators;


import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.validation.AbstractFormValidator;

public class ElectiveUniqueValidator extends AbstractFormValidator {

	private static final long serialVersionUID = 3415061105846455523L;
	private FormComponent<?>[] components;
	private int componentNum = 0;
	private int totalComponents = 0;
	
	public ElectiveUniqueValidator(){
		components = new FormComponent<?>[10];
		totalComponents = 10;
	}
	
	public void addComponent(FormComponent<Integer> component){
		if(componentNum<totalComponents)
			components[componentNum] = component;
		else{
			FormComponent<?>[] tempArray = new FormComponent<?>[totalComponents*2];
			for(int i=0;i<componentNum;i++){
				tempArray[i] = components[i];
			}
			totalComponents *=2;
			components[componentNum] = component;
		}
		componentNum++;
	}
	
	
	public FormComponent<?>[] getDependentFormComponents() {
		return components;
	}

	@SuppressWarnings("unchecked")
	public void validate(Form<?> arg0) {
		int[] checkArray = new int[componentNum];
		for(int i=0;i<componentNum;i++){
			TextField<Integer> tf = (TextField<Integer>) components[i];
			int num = Integer.parseInt(tf.getValue());
			if(num >= componentNum){
				error(components[0],"ChoiceGreaterThanSubjects");
				return;
			}
			if(checkArray[num] == 0){
				checkArray[num] = num;
			}else{
				error(components[0],"ElectiveChosenTwice");
				return;
			}
		}
	}

}
